import { FSMControl } from "../fsm/FSMControl";
import { FSMState } from "../fsm/State";

const { ccclass, property } = cc._decorator;

@ccclass
export default class HeroMove extends cc.Component {

    control: FSMControl = null

    _isOnGround: boolean = false;

    _attack:boolean=false;

    @property
    speed: number = 0;

    onLoad() {
        this.control = this.node.getComponent(FSMControl);
    }

    isOnGround() {
        return this._isOnGround;
    }
    input: Map<number, boolean>;

    start() {
        this.input = new Map();
        cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, this.keyDown, this);
        cc.systemEvent.on(cc.SystemEvent.EventType.KEY_UP, this.keyUp, this);
    }

    update(dt: number) {
        this.move(dt);
    }

    keyDown(key: cc.Event.EventKeyboard) {
        this.input.set(key.keyCode, true);
    }

    keyUp(key: cc.Event.EventKeyboard) {
        this.input.set(key.keyCode, false);
    }

    public getKey(key: number) {
        return this.input.get(key);
    }


  
    move(dt: number) {
        let rigidBody = this.node.getComponent(cc.RigidBody)

        let x = 0;
        if (this.input.get(cc.macro.KEY.left) ||
            this.input.get(cc.macro.KEY.a)) {
            x = -this.speed;
        }
        if (this.input.get(cc.macro.KEY.right) ||
            this.input.get(cc.macro.KEY.d)) {
            x = this.speed;
        }
        rigidBody.linearVelocity = cc.v2(x, rigidBody.linearVelocity.y)

        //跳跃
        if ((this.input.get(cc.macro.KEY.up) ||
            this.input.get(cc.macro.KEY.w)) &&
            this.isOnGround()) {        
            rigidBody.linearVelocity = cc.v2(rigidBody.linearVelocity.x, 900)
            this._isOnGround=false;
        }
        // if (this.input.get(cc.macro.KEY.down) ||
        //     this.input.get(cc.macro.KEY.s)) {
        //     this.node.y -= this.speed * dt
        // }
        //攻击
        if(this.input.get(cc.macro.KEY.j)){
            // let animation=this.node.getComponent(cc.Animation);
            // animation.play('hero_attack');
            // this.scheduleOnce(()=>{
                
            // },1);
        }
        //冲刺
        if(this.input.get(cc.macro.KEY.shift)){
            
        }

        if (x != 0) {
            this.control.fsmAction.state = FSMState.Walk
            this.node.scaleX=(x/Math.abs(x));
        }
        else {
            this.control.fsmAction.state = FSMState.Idle
        }
        if(!this.isOnGround()){
            this.control.fsmAction.state = FSMState.Jump
        }
    }

    onBeginContact(contact: cc.PhysicsContact, self: cc.PhysicsCollider, other: cc.PhysicsCollider) {
        if(other.node.group=='ground')
        this._isOnGround = true;
    }

}
